package cn.wangxl.vertx.starter.core.eventBus;

import io.vertx.core.Vertx;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.eventbus.MessageConsumer;

/**
 * eventBus 用于vertx实例之间的通信
 * @Deacription
 * @Author 20112128
 * @Date 2020/5/13 14:20
 **/
public class EventBusVerticle {
  public static void main(String[] args) {
    Vertx vertx = Vertx.vertx();

    EventBus eventBus = vertx.eventBus();

    MessageConsumer<String> consumer = eventBus.consumer("news");

    consumer.handler(message -> {
      System.out.println("news,I have received a message: " + message.body());
    });

    new Thread(()->{
      while(true){
        try {
          Thread.sleep(5000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        EventBus reply = eventBus.publish("boys", "hello hello");
      }
    }).start();


    Vertx vertx1 = Vertx.vertx();

    EventBus eventBus1 = vertx1.eventBus();

    MessageConsumer<String> consumer1 = eventBus1.consumer("boys");

    consumer1.handler(message -> {
      System.out.println("boys,I have received a message: " + message.body());
    });

    new Thread(()->{
      while(true){
        try {
          Thread.sleep(5000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        eventBus1.publish("boys","hello");
      }
    }).start();


    Vertx vertx2 = Vertx.vertx();

    EventBus eventBus2 = vertx2.eventBus();

    MessageConsumer<String> consumer2 = eventBus2.consumer("boys");

    consumer2.handler(message -> {
      System.out.println("boys,I have received a message: " + message.body());
    });

  }
}
